﻿using Authority.Model;
using Common.Library;
using Dapper.MsSql.Library;
using AutoMapper.DTO;
using Sql.DataBase;
using System.Collections.Generic;
using System.Linq;
using Tool.Model;
using Dapper.MySql.Library;
using Encrypt.Library;

namespace Authority.Logic
{
    /// <summary>
    /// 部门管理逻辑
    /// </summary>
    public class SysDepartmentServiceImpl : ISysDepartmentService
    {
        #region 查询信息

        /// <summary>
        /// 根据Name获取部门列表信息
        /// </summary>
        /// <param name="parametersInfo"></param>
        /// <returns></returns>
        public ResultJsonInfo<List<DepartmentsListResponse>> LoadListInfo(string sName)
        {
            var resultInfo = new ResultJsonInfo<List<DepartmentsListResponse>>();

            List<SysDepartmentEntity> listInfo = null;
            using (var con = MySqlDataBase.GetConnection(DatabaseName.AuthorityDB_MySql))
            //using (var con = MsSqlDataBase.GetConnection(DatabaseName.AuthorityDB_MsSql))
            {
                if (sName.IsNotNullOrEmpty())
                {
                    var allInfo = con.QuerySet<SysDepartmentEntity>().AndWhere(p => p.bIsDeleted == false).OrderByAsc("iSort").Multiple();
                    var rootInfo = allInfo.FindAll(p => p.sName.Contains(sName));
                    listInfo = new List<SysDepartmentEntity>();
                    if (rootInfo.Count > 0)
                    {
                        listInfo.AddRange(rootInfo);
                        listInfo.AddRange(allInfo.GetChildList(rootInfo));
                    }
                    listInfo = listInfo.Distinct().ToList();
                }
                else
                {
                    listInfo = con.QuerySet<SysDepartmentEntity>().AndWhere(p => p.bIsDeleted == false).OrderByAsc("iSort").Multiple();
                }
            }

            if (listInfo.Count > 0)
            {
                var menusList = listInfo.MapToList<DepartmentsListResponse>();
                foreach (var item in menusList)
                {
                    //NET算术运算溢出问题
                    item.bHaveElder = listInfo.Exists(p => p.iSort < item.iSort && p.gCode != item.gCode && p.gParentCode == item.gParentCode);
                    item.bHaveYounger = listInfo.Exists(p => p.iSort > item.iSort && p.gCode != item.gCode && p.gParentCode == item.gParentCode);
                }
                resultInfo.Code = ActionCodes.Success;
                resultInfo.Data = menusList;
                resultInfo.Count = menusList.Count;
                resultInfo.Msg = "获取成功！";
            }
            else
            {
                resultInfo.Msg = "获取失败！";
            }
            return resultInfo;
        }

        /// <summary>
        /// 获取部门树状列表信息
        /// </summary>
        /// <returns></returns>
        public ResultJsonInfo<List<TreeInfo>> LoadTreeListInfo()
        {

            var resultInfo = new ResultJsonInfo<List<TreeInfo>>();

            List<TreeInfo> listInfo = new List<TreeInfo>();

            using (var con = MySqlDataBase.GetConnection(DatabaseName.AuthorityDB_MySql))
            //using (var con = MsSqlDataBase.GetConnection(DatabaseName.AuthorityDB_MsSql))
            {
                var departments = con.QuerySet<SysDepartmentEntity>().AndWhere(p => p.bIsDeleted == false).OrderByAsc("iSort").Multiple();

                if (departments.Count > 0)
                {
                    string md5hash = SecurityHelper.GetMD5Hash();
                    TreeInfo departmentInfo = new TreeInfo()
                    {
                        id = "",
                        title = "公司岗位信息",
                        field = "公司岗位信息",
                        spread = "true",
                        children = departments.GetChildTreeInfo<SysDepartmentEntity>(md5hash)
                    };
                    listInfo.Add(departmentInfo);
                    resultInfo.Code = ActionCodes.Success;
                    resultInfo.Data = listInfo;
                    resultInfo.Msg = "获取成功！";
                }
                else
                {
                    resultInfo.Msg = "获取失败！";
                }
            }
            return resultInfo;
        }

        /// <summary>
        /// 获取部门树状列表信息
        /// </summary>
        /// <returns></returns>
        public ResultJsonInfo<List<SelectListInfo>> LoadSelectListInfo()
        {

            var resultInfo = new ResultJsonInfo<List<SelectListInfo>>();

            List<SelectListInfo> listInfo = new List<SelectListInfo>();

            using (var con = MySqlDataBase.GetConnection(DatabaseName.AuthorityDB_MySql))
            //using (var con = MsSqlDataBase.GetConnection(DatabaseName.AuthorityDB_MsSql))
            {
                var departments = con.QuerySet<SysDepartmentEntity>()
                                    .AndWhere(p => p.bIsDeleted == false)
                                    .OrderByAsc("iSort")
                                    .Multiple();

                if (departments.Count > 0)
                {
                    var department = departments.Find(p => p.gParentCode == null);
                    SelectListInfo departmentInfo = new SelectListInfo()
                    {
                        value = department.gCode,
                        name = department.sName,
                        children = departments.GetSelectChildInfo<SysDepartmentEntity>(department.gCode)
                    };
                    listInfo.Add(departmentInfo);
                    resultInfo.Code = ActionCodes.Success;
                    resultInfo.Data = listInfo;
                    resultInfo.Msg = "获取成功！";
                }
                else
                {
                    resultInfo.Msg = "获取失败！";
                }
            }
            return resultInfo;
        }
        #endregion

        #region 节点编辑操作

        /// <summary>
        /// 新增根节点信息
        /// </summary>
        /// <param name="parameters"></param>
        /// <returns></returns>
        public ResultJsonInfo<int> AddRoot(DepartmentRootRequest inputInfo)
        {
            var resultInfo = new ResultJsonInfo<int>();

            using (var con = MySqlDataBase.GetConnection(DatabaseName.AuthorityDB_MySql))
            //using (var con = MsSqlDataBase.GetConnection(DatabaseName.AuthorityDB_MsSql))
            {
                var result = 0;

                var sysDepartment = inputInfo.MapTo<SysDepartmentEntity>();
                //获取所有部门信息
                var sysDepartmentResult = con.QuerySet<SysDepartmentEntity>().WithNoLock().Multiple();
                var sysDepartmentRootInfo = sysDepartmentResult.Find(p => p.gParentCode == null); ;

                int maxSort = 0;
                if (sysDepartmentResult.Count > 0)
                {
                    maxSort = sysDepartmentResult.Select(p => p.iSort).Max();
                }
                sysDepartment.gCode = GuidHelper.GetGuid();
                sysDepartment.gParentCode = SecurityHelper.GetMD5Hash(); 
                sysDepartment.iSort = maxSort + 1;

                result = con.CommandSet<SysDepartmentEntity>().Insert(sysDepartment);

                if (result > 0)
                {
                    resultInfo.Code = ActionCodes.Success;
                    resultInfo.Data = result;
                    resultInfo.Msg = "新增根节点信息成功！";
                }
                else
                {
                    resultInfo.Msg = "操作失败！";
                }
            }
            return resultInfo;
        }

        /// <summary>
        /// 新增子节点信息
        /// </summary>
        /// <param name="parameters"></param>
        /// <returns></returns>
        public ResultJsonInfo<int> AddChild(DepartmentChildRequest inputInfo)
        {
            var resultInfo = new ResultJsonInfo<int>();

            using (var con = MySqlDataBase.GetConnection(DatabaseName.AuthorityDB_MySql))
            //using (var con = MsSqlDataBase.GetConnection(DatabaseName.AuthorityDB_MsSql))
            {
                con.Transaction(tran =>
                {
                    var result = 0;

                    var sysDepartment = inputInfo.MapTo<SysDepartmentEntity>();
                    var sysDepartmentResult = tran.QuerySet<SysDepartmentEntity>().WithNoLock().Multiple();

                    //查询出排序在该节点之后的所有节点
                    var sysDepartmentInfos = sysDepartmentResult.FindAll(p => p.iSort >= sysDepartment.iSort);
                    foreach (var item in sysDepartmentInfos)
                    {
                        item.iSort = short.Parse((item.iSort + short.Parse("1")).ToString());
                        tran.CommandSet<SysDepartmentEntity>().Update(item);
                    }

                    //插入数据
                    sysDepartment.gCode = GuidHelper.GetGuid();
                    result = tran.CommandSet<SysDepartmentEntity>().Insert(sysDepartment);

                    if (result > 0)
                    {
                        resultInfo.Code = ActionCodes.Success;
                        resultInfo.Data = result;
                        resultInfo.Msg = "新增子节点信息成功！";
                    }
                    else
                    {
                        resultInfo.Msg = "操作失败！";
                    }
                });

            }
            return resultInfo;
        }

        /// <summary>
        /// 修改信息
        /// </summary>
        /// <param name="parameters"></param>
        /// <returns></returns>
        public ResultJsonInfo<int> Modify(DepartmentModifyRequest inputInfo)
        {
            var resultInfo = new ResultJsonInfo<int>();

            using (var con = MySqlDataBase.GetConnection(DatabaseName.AuthorityDB_MySql))
            //using (var con = MsSqlDataBase.GetConnection(DatabaseName.AuthorityDB_MsSql))
            {
                var result = 0;

                var sysDepartment = inputInfo.MapTo<SysDepartmentEntity>();

                var sysDepartmentInfo = con.QuerySet<SysDepartmentEntity>().AndWhere(p => p.gCode == sysDepartment.gCode).Single();
                if (sysDepartmentInfo != null)
                {
                    sysDepartmentInfo.sName = sysDepartment.sName;
                    sysDepartmentInfo.sLeader = sysDepartment.sLeader;
                    sysDepartmentInfo.sPhone = sysDepartment.sPhone;
                    sysDepartmentInfo.sEmail = sysDepartment.sEmail;
                    sysDepartmentInfo.sContent = sysDepartment.sContent;
                    sysDepartmentInfo.bIsEnabled = sysDepartment.bIsEnabled;
                    result = con.CommandSet<SysDepartmentEntity>().Update(sysDepartmentInfo);
                }
                else
                {
                    resultInfo.Msg = "无对应信息！";
                }
                if (result > 0)
                {
                    resultInfo.Code = ActionCodes.Success;
                    resultInfo.Data = result;
                    resultInfo.Msg = "修改信息成功！";
                }
                else
                {
                    resultInfo.Msg = "操作失败！";
                }
            }
            return resultInfo;
        }
        #endregion

        #region 移动顺序操作
        /// <summary>
        /// 移动顺序操作
        /// </summary>
        /// <param name="parameters"></param>
        /// <returns></returns>
        public ResultJsonInfo<int> Move(DepartmentMoveRequest inputInfo)
        {

            var result = new ResultJsonInfo<int>();

            using (var con = MySqlDataBase.GetConnection(DatabaseName.AuthorityDB_MySql))
            //using (var con = MsSqlDataBase.GetConnection(DatabaseName.AuthorityDB_MsSql))
            {
                con.Transaction(tran =>
                {
                    //（1）所有功能
                    var adminDepartments = tran.QuerySet<SysDepartmentEntity>().AndWhere(p => p.bIsDeleted == false).OrderByAsc("iSort").Multiple();

                    //（2）当前功能 
                    SysDepartmentEntity currAdminDepartment = adminDepartments.Find(p => p.gCode == inputInfo.Code);

                    //（3）当前功能兄弟节点
                    List<SysDepartmentEntity> brothersAdminDepartment = adminDepartments.FindAll(p => p.gParentCode == currAdminDepartment.gParentCode);

                    SysDepartmentEntity broAdminDepartment = null;

                    foreach (SysDepartmentEntity item in brothersAdminDepartment)
                    {
                        if (inputInfo.Flag == 1)//上移
                        {
                            if (item.iSort < currAdminDepartment.iSort) { broAdminDepartment = item; }
                            if (item.iSort > currAdminDepartment.iSort) { break; } //找到上一个兄弟节点
                        }
                        else //下移
                        {
                            if (item.iSort > currAdminDepartment.iSort) { broAdminDepartment = item; break; } //找到下一个兄弟节点
                        }
                    }

                    List<SysDepartmentEntity> currFuns = new List<SysDepartmentEntity>();
                    currFuns.Add(currAdminDepartment);
                    GetMoveNode(adminDepartments, currAdminDepartment.gCode, currFuns);

                    List<SysDepartmentEntity> moveFuns = new List<SysDepartmentEntity>();
                    moveFuns.Add(broAdminDepartment);
                    GetMoveNode(adminDepartments, broAdminDepartment.gCode, moveFuns);

                    //上移
                    if (inputInfo.Flag == 1)
                    {
                        foreach (SysDepartmentEntity item in currFuns)
                        {
                            item.iSort = short.Parse((item.iSort - short.Parse(moveFuns.Count.ToString())).ToString());
                            tran.CommandSet<SysDepartmentEntity>().Update(item);
                        }

                        foreach (SysDepartmentEntity item in moveFuns)
                        {
                            item.iSort = short.Parse((item.iSort + short.Parse(currFuns.Count.ToString())).ToString());
                            tran.CommandSet<SysDepartmentEntity>().Update(item);
                        }
                    }
                    else
                    {
                        foreach (SysDepartmentEntity item in currFuns)
                        {
                            item.iSort = short.Parse((item.iSort + short.Parse(moveFuns.Count.ToString())).ToString());
                            tran.CommandSet<SysDepartmentEntity>().Update(item);
                        }
                        foreach (SysDepartmentEntity item in moveFuns)
                        {
                            item.iSort = short.Parse((item.iSort - short.Parse(currFuns.Count.ToString())).ToString());
                            tran.CommandSet<SysDepartmentEntity>().Update(item);
                        }
                    }
                });
                result.Code = ActionCodes.Success;
                result.Data = 1;
            }
            return result;
        }

        /// <summary>
        /// 上下一定子功能（递归）
        /// </summary>
        /// <param name="adminFuns"></param>
        /// <param name="funId"></param>
        /// <param name="move"></param>
        private void GetMoveNode(List<SysDepartmentEntity> adminDepartments, string funId, List<SysDepartmentEntity> move)
        {
            List<SysDepartmentEntity> borgs = adminDepartments.FindAll(r => r.gParentCode == funId);
            foreach (SysDepartmentEntity item in borgs)
            {
                if (item.gParentCode == funId)
                {
                    move.Add(item);
                    List<SysDepartmentEntity> tempFuns = adminDepartments.FindAll(r => r.gParentCode == item.gCode);
                    if (tempFuns != null && tempFuns.Count > 0)
                    {
                        GetMoveNode(adminDepartments, item.gCode, move);
                    }
                }
            }
        }
        #endregion

        #region 删除信息
        /// <summary>
        /// 删除信息
        /// </summary>
        /// <param name="parameters"></param>
        /// <returns></returns>
        public ResultJsonInfo<int> Remove(List<string> gCodeList)
        {
            var resultInfo = new ResultJsonInfo<int>();

            using (var con = MySqlDataBase.GetConnection(DatabaseName.AuthorityDB_MySql))
            //using (var con = MsSqlDataBase.GetConnection(DatabaseName.AuthorityDB_MsSql))
            {
                var result = 0;
                if (gCodeList.Count >= 0)
                {
                    //var listCode = con.QuerySql<string>().BySql(DataCommandManager.GetSQLCommand("LoadDepartmentsByCodes", "SysDepartment"),
                    //       new
                    //       {
                    //           gCodeList = gCodeList
                    //       }).Multiple();

                    con.Transaction(tran =>
                    {

                        var listInfo = new List<SysDepartmentEntity>();
                        var allInfo = tran.QuerySet<SysDepartmentEntity>().AndWhere(p => p.bIsDeleted == false && p.bIsEnabled == true).Multiple();
                        var rootInfo = allInfo.FindAll(p => gCodeList.Contains(p.gCode));
                        if (rootInfo.Count > 0)
                        {
                            listInfo.AddRange(rootInfo);
                            listInfo.AddRange(allInfo.GetChildList(rootInfo));
                        }
                        var listCode = listInfo.Select(p => p.gCode).ToList();

                        bool existInfo = tran.QuerySet<SysUserDepartmentEntity>().AndWhere(p => listCode.Contains(p.gDepartmentCode)).Exists();
                        if (existInfo)
                        {
                            result = tran.CommandSet<SysDepartmentEntity>().AndWhere(p => listCode.Contains(p.gCode))
                                                                           .UpdateByExp(p => new SysDepartmentEntity
                                                                           {
                                                                               bIsDeleted = true
                                                                           });
                            if (result > 0)
                            {
                                resultInfo.Code = ActionCodes.Success;
                                resultInfo.Data = result;
                                resultInfo.Msg = "操作成功！";
                            }
                            else
                            {
                                resultInfo.Msg = "操作失败！";
                            }
                        }
                        else
                        {
                            resultInfo.Msg = "选中部门已被已被用户使用，无法删除！";
                        }
                    });
                }
                else
                {
                    resultInfo.Msg = "id为空，操作失败！";
                }
            }
            return resultInfo;
        }
        #endregion

    }
}
